<template>
    <div class="sign-board">
        <canvas
            id="canvas"
            ref="canvas"
            width="800"
            height="600"
            class="canvas"
            @mousedown="canvasDown($event)"
            @mousemove="canvasMove($event)"
            @mouseup="canvasUp($event)"
            @mouseleave="canvasLeave($event)"
        />
        <div class="canvas-btn">
            <el-button @click="canvasClear">重写</el-button>
            <el-button type="primary" @click="canvasDownTap">完成</el-button>
        </div>
    </div>
</template>

<script>
    export default {
        name: "SignBoard",
        props: {

        },
        data() {
            return {

            };
        },
        computed: {

        },
        mounted() {
            this.initCanvas();
        },
        methods: {
            initCanvas() {
                this.canvas = this.$refs.canvas;// 指定canvas
                this.ctx = this.canvas.getContext("2d");// 设置2D渲染区域
                this.ctx.lineWidth = 5;// 设置线的宽度
            },
            canvasDown(e) {
                this.canvasMoveUse = true;
                const canvasX = e.clientX - e.target.offsetLeft;
                const canvasY = e.clientY - e.target.offsetTop + document.documentElement.scrollTop;
                this.ctx.beginPath(); // 移动的起点
                this.ctx.moveTo(canvasX, canvasY);
            },
            canvasMove(e) {
                if (this.canvasMoveUse) {
                    // 只有允许移动时调用
                    const t = e.target;
                    let canvasX;
                    let canvasY;
                    canvasX = e.clientX - t.offsetLeft;
                    canvasY = e.clientY - t.offsetTop + document.documentElement.scrollTop;
                    this.ctx.lineTo(canvasX, canvasY);
                    this.ctx.stroke();
                }
            },
            canvasUp() {
                this.canvasMoveUse = false;
            },
            canvasLeave() {
                this.canvasMoveUse = false;
            },
            canvasClear() {
                this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height);
            },
            canvasDownTap() {
                let _src = this.$refs.canvas.toDataURL("image/png");
                this.$emit("canvasDownTap", _src);
            }
        }
    };
</script>

<style scoped lang="scss">
    .sign-board {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0px;
        left: 0px;
        background-color: rgba(0, 0, 0, 0.7);
        z-index: 3;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }
    .canvas {
        background-color: #ffffff;
    }
    .canvas-btn{
        button {
            margin: 0px 50px;
        }
    }
</style>
